/*
 * Android Simple Music player
   Copyright hayoon.ko (shauku@naver.com)

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package kr.ac.kaist.simplemusicplayer;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

class Mp3Filter implements FilenameFilter {
    public boolean accept(File dir, String name) {
            return (name.endsWith(".mp3"));
    }
}


/**
 * Music List Activity - display music info & album art - when selected, request svc to
 * play music & start music controller activity
 * @author shauku@naver.com
 * @version 10
 *
 */
public class MusicList extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_music_list);
		
		ctx = this;
		
//		startService(new Intent(MusicList.this, SMPService.class));		
        bindService(new Intent(MusicList.this, SMPService.class),mConnection,Context.BIND_AUTO_CREATE);
        
        Button toPlayer = (Button)findViewById(R.id.toplayer);
        toPlayer.setVisibility(Button.INVISIBLE);
	}
	
	protected void onDestroy(){
		super.onDestroy();
		unbindService(mConnection);
	}

	
    
    /**
     * when activity is up, read all music files and send meta info to service 
     * use content resolver to extract each song's meta info from content provider via content resolver
     */  	
	public void updateSongList() {
		mp3_resolver = getContentResolver();
	
		
		/*query content provider "Mediastore" to get music list stored in EXTERNAL SD card */
		
		mp3_cursor = mp3_resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,mCursorCols,
				MediaStore.MediaColumns.MIME_TYPE+"='"+"audio/mpeg"+"'",null,null);

		int count = mp3_cursor.getCount();
		
		if(count >0){
    		TextView emptyString = (TextView)findViewById(R.id.empty_string);
    		emptyString.setVisibility(TextView.INVISIBLE);
    		
            Button toPlayer = (Button)findViewById(R.id.toplayer);
            toPlayer.setVisibility(Button.VISIBLE);   
            toPlayer.setOnClickListener(new OnClickListener(){
            	public void onClick(View v){
            		Intent intent = new Intent(getApplicationContext(),MusicControl.class);
            		intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            		startActivity(intent);
            	}
            });  
		}
		else
		{
    		TextView emptyString = (TextView)findViewById(R.id.empty_string);
    		emptyString.setVisibility(TextView.VISIBLE);			
		}
		
		
		if(count > max_mp3num)
			count = max_mp3num;
		
		if(mp3_cursor.moveToFirst()){	
			
			//reset playlist in service
			try{
				smpInterface.clearPlaylist();
			}catch(Exception  e){
	   			Log.e(getString(R.string.app_name), e.getMessage());                		
        	}  
			
			itemList = new ArrayList<MusicInfoItem>();
			
			while(count>0){
				String title = "", artist, album, path,id;
				
				int titleColumn = mp3_cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
				int artistColumn = mp3_cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
				int albumColumn = mp3_cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);
				int dataColumn = mp3_cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
				int idColumn = mp3_cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID);
				
				if(titleColumn <0)
					title = STRING_UNKNOWN;
				else
					title = mp3_cursor.getString(titleColumn);

				if(artistColumn <0)
					artist = STRING_UNKNOWN;
				else
					artist = mp3_cursor.getString(artistColumn);
				
				if(albumColumn <0)
					album = STRING_UNKNOWN;
				else
					album = mp3_cursor.getString(albumColumn);
				
				if(dataColumn <0)
					path = STRING_UNKNOWN;
				else
					path = mp3_cursor.getString(dataColumn);
				if(idColumn <0)
					id = STRING_UNKNOWN;
				else
					id = mp3_cursor.getString(idColumn);
				
				title_list.add(title);
				id_list.add(id);
				song_path_list.add(path);
				
				itemList.add(new MusicInfoItem(title, id, artist));
				
				mp3_cursor.moveToNext();		
            	try{
            		smpInterface.addSongPlaylist(path, id, title);           
            	}
            	catch(Exception  e){
    	   			Log.e(getString(R.string.app_name), e.getMessage());                		
            	}         	
				count--;
			}


/*display 3 meta info of one music item in one arraylist*/			
    		listViewRest = (ListView)findViewById( R.id.music_list);
    		
            listViewRest.setAdapter(new MusicListAdapter(ctx, R.layout.song_item, itemList));
            
    		listViewRest.setOnItemClickListener(new OnItemClickListener() {
    	          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
       	           try{
     	    			 smpInterface.playFile(position);
     	    			}
      	           catch(Exception  e){
      	   			Log.e(getString(R.string.app_name), e.getMessage());
      	           }	 
    	        	  Intent intent = new Intent(getApplicationContext(), MusicControl.class);
              		  intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
   	 	  			  startActivity(intent);
    	          }
    	    });			
			
		}	    
	}
	

	private ServiceConnection mConnection = new ServiceConnection()
    {
		public void onServiceConnected(ComponentName className, IBinder service) {
			smpInterface = SMPInterface.Stub.asInterface((IBinder)service);
			updateSongList();}

		public void onServiceDisconnected(ComponentName className) {
			smpInterface = null;
		}
    };


    String[] mCursorCols = new String[]{
    		MediaStore.Audio.Media._ID,
    		MediaStore.Audio.Media.ARTIST,
    		MediaStore.Audio.Media.TITLE,
    		MediaStore.Audio.Media.ALBUM,
    		MediaStore.Audio.Media.DATA,
    		MediaStore.Audio.Media.ALBUM_ID
    };
    
    private ContentResolver mp3_resolver;
    private Cursor mp3_cursor;
	
	public static final String MEDIA_PATH = new String("/storage/sdcard0/");
	public static final int max_mp3num = 100;
	public static final String STRING_UNKNOWN = new String("Unknown");
	private List<String> title_list = new ArrayList<String>();
	private List<String> id_list = new ArrayList<String>();
	private List<String> song_path_list = new ArrayList<String>();	
	private SMPInterface smpInterface;
	private int currentPosition = 0;
	
	Context ctx;
	private ListView listViewRest;
	List<MusicInfoItem> itemList;
}


